#
# This file is part of the kernelstudio package.
#
# (c) 2014-2025 zlin <admin@kernelstudio.com>
#
# For the full copyright and license information, please view the LICENSE file
# that was distributed with this source code.
from flask import jsonify, current_app

from api.utils.request_params_parser import parse_request_attachments, parse_request_attachment
from ksai.document.ocr.factory import ocr_factory
from ksai.web.api import ApiResource


class DocumentOcrController(ApiResource):

    def post(self):
        try:
            attachment = parse_request_attachment()
            content = ocr_factory.execute(attachment)
            return jsonify({"text": content})
        except Exception as e:
            current_app.logger.error(f"OCR 处理失败: {str(e)}")
            return jsonify({"error": "处理失败"}), 500


class DocumentOcrBatchController(ApiResource):

    def post(self):
        attachments = parse_request_attachments()
        data = []
        for attachment in attachments:
            content = ocr_factory.execute(attachment)
            data.append({
                'uuid': attachment.uuid,
                'sign': attachment.sign,
                'filename': attachment.filename,
                'size': attachment.size,
                'mime': attachment.mime,
                'suffix': attachment.suffix,
                'content': content
            })
        return self.make_success(data)
